package com.leyu.mall.site.user.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.leyu.mall.domain.user.UserBase;
import com.leyu.mall.service.user.UserService;

/**
 * 用户注册
 * 
 * @author change
 * 
 */
@Controller
@RequestMapping(value = "/register")
public class RegisterController {

	@Autowired
	private UserService userService;
	@RequestMapping(method = RequestMethod.GET)
	public String register(
			RedirectAttributes redirectAttributes) { 
		return "user/register.html";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String register(@Valid RegisterForm registerForm,
			RedirectAttributes redirectAttributes) {
		try {
			
			boolean result=userService.registerUser(createMember(registerForm));
			redirectAttributes.addFlashAttribute("username",
					registerForm.getUsername());
			if(result){
				return "redirect:/login";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "user/register.html";
	}

	private UserBase createMember(RegisterForm form) {
		UserBase user = new UserBase();
		user.setPassword(form.password);
		user.setUsername(form.getUsername());
		user.setUserEmail(form.getUsername());

		return user;
	}

	/**
	 * Ajax请求校验loginName是否唯一。
	 */
	@RequestMapping(value = "checkLoginName")
	@ResponseBody
	public String checkLoginName(@RequestParam("loginName") String loginName) {
		if (userService.findByLoginName(loginName) == null) {
			return "true";
		} else {
			return "false";
		}
	}

	public static class RegisterForm {
		private String username;
		private String password;
		private String password2;
		private String email;
		private String mobile;

		public String getUsername() {
			return username;
		}

		public void setUsername(String username) {
			this.username = username;
		}

		public String getPassword() {
			return password;
		}

		public void setPassword(String password) {
			this.password = password;
		}

		public String getPassword2() {
			return password2;
		}

		public void setPassword2(String password2) {
			this.password2 = password2;
		}

		public String getEmail() {
			return email;
		}

		public void setEmail(String email) {
			this.email = email;
		}

		public String getMobile() {
			return mobile;
		}

		public void setMobile(String mobile) {
			this.mobile = mobile;
		}

	}
}
